package cn.iocoder.yudao.module.vos.dal.mysql.marketinglistlog;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.vos.dal.dataobject.marketinglistlog.MarketingListLogDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.vos.controller.admin.marketinglistlog.vo.*;
import org.apache.ibatis.annotations.Param;

/**
 * 营销名单日志表（含应答状态） Mapper
 *
 * @author shijun
 */
@Mapper
public interface MarketingListLogMapper extends BaseMapperX<MarketingListLogDO> {

    default PageResult<MarketingListLogDO> selectPage(MarketingListLogPageReqVO reqVO) {
        LambdaQueryWrapperX<MarketingListLogDO> qw = new LambdaQueryWrapperX<MarketingListLogDO>().eqIfPresent(MarketingListLogDO::getPhoneE164, reqVO.getPhoneE164()).eqIfPresent(MarketingListLogDO::getScore, reqVO.getScore()).betweenIfPresent(MarketingListLogDO::getCreateTime, reqVO.getCreateTime()).eqIfPresent(MarketingListLogDO::getPhoneMd5, reqVO.getPhoneMd5()).eqIfPresent(MarketingListLogDO::getSecretId, reqVO.getSecretId()).betweenIfPresent(MarketingListLogDO::getResponseTime, reqVO.getResponseTime()).eqIfPresent(MarketingListLogDO::getResponseState, reqVO.getResponseState()).eqIfPresent(MarketingListLogDO::getRechargeTenantId, reqVO.getRechargeTenantId()).eqIfPresent(MarketingListLogDO::getListLevel, reqVO.getListLevel());

        // phone_tags CSV：ANY 命中（FIND_IN_SET）
        if (reqVO.getPhoneTags() != null && !reqVO.getPhoneTags().isEmpty()) {
            qw.and(w -> {
                for (int i = 0; i < reqVO.getPhoneTags().size(); i++) {
                    String tag = reqVO.getPhoneTags().get(i);
                    if (i == 0) {
                        w.apply("FIND_IN_SET({0}, phone_tags) > 0", tag);
                    } else {
                        w.or().apply("FIND_IN_SET({0}, phone_tags) > 0", tag);
                    }
                }
            });
        }

        // list_date（VARCHAR，期望 yyyy-MM-dd）：仅在传入时过滤
        if (reqVO.getListDate() != null && reqVO.getListDate().length > 0) {
            LocalDate start = reqVO.getListDate()[0];
            LocalDate end = (reqVO.getListDate().length >= 2 && reqVO.getListDate()[1] != null) ? reqVO.getListDate()[1] : start;
            if (start != null) {
                qw.ge(MarketingListLogDO::getListDate, start.toString()); // yyyy-MM-dd
            }
            if (end != null) {
                qw.le(MarketingListLogDO::getListDate, end.toString());
            }
        }

        qw.orderByDesc(MarketingListLogDO::getId); // 按 ID 降序
        return selectPage(reqVO, qw);
    }

    // —— 新增：仅按 (tenantId + phoneE164) 判断存在 —— //

    /**
     * 仅按 (tenant + phoneE164 + listDate) 判断是否已存在
     */
    Long selectIdByTenantPhoneDate(@Param("rechargeTenantId") Long rechargeTenantId, @Param("phoneE164") String phoneE164, @Param("listDate") String listDate);

    /**
     * 命中仅更新：score / phone_tags / list_level（listLevel 为 String）
     */
    int updateWithoutResponseById(@Param("id") Long id, @Param("score") BigDecimal score, @Param("phoneTags") String phoneTags, @Param("listLevel") String listLevel, @Param("marketingTools") String marketingTools); // 新增字段


    // 更新 responseState 和 responseTime
    int updateResponseStateAndTime(@Param("phoneMd5") String phoneMd5, @Param("tenantId") Long tenantId, @Param("responseState") Integer responseState, @Param("responseTime") LocalDateTime responseTime, @Param("secretId") Long secretId);

    List<MarketingListLogDO> selectListByPhoneMd5AndTenant(@Param("phoneMd5") String phoneMd5, @Param("tenantId") Long tenantId);


    List<MarketingListLogDO> selectByTenantAndCreateDate(@Param("day") LocalDate day,
                                                         @Param("tenantId") Long tenantId,
                                                         @Param("offset") int offset,
                                                         @Param("limit") int limit);

    Long countByTenantAndCreateDate(@Param("day") LocalDate day,
                                    @Param("tenantId") Long tenantId);
}